package mysql

import (
	"errors"
	"fmt"
)

type Role struct {
	Id         uint `gorm:"column:id;primary_key" json:"id" form:"id"`
	Status     int  `gorm:"column:status" json:"status" form:"status"`
	Deleted    int  `gorm:"column:deleted" json:"deleted"`
	AddTime    int32 `gorm:"column:add_time" json:"add_time"`
	UpdateTime int32 `gorm:"column:update_time" json:"update_time"`
	Memo       string `gorm:"column:memo" json:"memo" form:"memo"`
	Name string `gorm:"column:name" json:"name"`
	Px   int    `gorm:"column:px" json:"px"`

}

//这一步的意思是改表明的  默认表明是带s的
func (Role) TableName() string {
	return "k_admin_role"
}

func (a Role) GetLists() ([]Role,error) {
	list := []Role{}
	db:= Db
	err := db.Find(&list).Error
	if err != nil {
		return nil,err
	}
    return list,err
}

func (model Role) GetList(where []map[string]interface{}, page int, pageSize int) (map[string]interface{}, error) {

	if page <= 0 {
		return nil, errors.New("page 不正确")
	}
	if page == 1 {
		page = 0
	}
	result := map[string]interface{}{}
	db := Db
	num := 0
	RoleArray := []Role{}
	offset := (page - 1) * pageSize

	for _, m := range where {
		db = db.Where(m["filed"].(string)+" "+m["exp"].(string)+" ?", m["val"])
	}

	err := db.Model(&Role{}).Count(&num).Limit(pageSize).Offset(offset).Find(&RoleArray).Error
	if err == nil {
		result["data"] = RoleArray
		result["count"] = num
	}
	return result, err

}

func (model Role) GetAdminByAccount(account string) (Role, error) {
	var Role Role
	err := Db.Where("account = ?", account).Find(&Role).Error
	if err != nil {
		fmt.Println("查询错误", err)
		return Role, err
	}
	return Role, err
}

func (model Role) Sort(id int, px int) error {
	db := Db
	Role := Role{}
	err := db.Model(&Role).Where("id = ?", id).Update("px", px).Error
	return err
}

func (model Role) SetStatus(id int, status int) error {
	db := Db
	Role := Role{}
	err := db.Model(&Role).Where("id = ?", id).Update("status", status).Error
	return err
}

func (n Role) Add(Role Role) error {
	db := Db
	err := db.Create(&Role).Error
	return err
}

func (model Role) Save(Role Role) error {
	db := Db
	err := db.Save(&Role).Error
	return err
}

func (model Role) Del(id int) error {
	db := Db
	Role := Role{}
	err := db.Where("id = ?", id).Delete(&Role).Error
	return err
}

func (model Role) GetItemById(id int) (Role, error) {

	db := Db
	Role := Role{}
	err = db.Find(&Role, id).Error
	if err != nil {
		fmt.Println("查询错误", err)
		return Role, err
	}
	return Role, err
}
